package com.overkill.game;

import android.os.SystemClock;

public class RenderThread extends Thread {

	// private static final int AVERAGE_FPS_SIZE = 500;
	// private int[] AVERAGE_FPS = new int[AVERAGE_FPS_SIZE];
	// private int AVERAGE_FPS_POS = 0;

	private int targetFps;
	private int frameDelay;
	
	private long lastRenderTime = 0;
	
	private RenderView view;
	private boolean run;
	private boolean wait;

	public RenderThread(RenderView view) {
		this.view = view;
	}
	
	public RenderThread(RenderView view, int tragetFps) {
		this.view = view;
		this.targetFps = tragetFps;
		this.frameDelay = 1000 / tragetFps;
	}

	public void startRender() {
		this.run = true;
		this.start();
	}

	public void pauseRender() {
		this.pauseRender(false);
	}

	public void pauseRender(boolean renderBefore) {
		if (renderBefore) {
			this.view.render(SystemClock.elapsedRealtime(), 0);
		}
		this.wait = true;
		synchronized (this) {
			this.notify();
		}
	}

	public void resumeRender() {
		this.wait = false;
		synchronized (this) {
			this.notify();
		}
	}

	public void stopRender() {
		this.run = false;
		synchronized (this) {
			this.notify();
		}
	}

	@Override
	public void run() {
		while (this.run) {
			long renderStartTime = SystemClock.elapsedRealtime();
			int deltaTime = 0;
			if(lastRenderTime != 0)
				deltaTime = (int) (renderStartTime - lastRenderTime);
			
			lastRenderTime = renderStartTime;
			this.view.render(renderStartTime, deltaTime);
			long cycleTime = SystemClock.elapsedRealtime() - renderStartTime;
			long sleep = Math.max(0, frameDelay - cycleTime);
			try {
				sleep(sleep);
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
			synchronized (this) {
				if (wait) {
					try {
						wait();
					} catch (Exception e) {
					}
				}
			}
		}
	}

	public int getTargetFps() {
		return targetFps;
	}

	public void setTargetFps(int targetFps) {
		this.targetFps = targetFps;
		this.frameDelay = 1000 / targetFps;
	}

	public int getFrameDelay() {
		return frameDelay;
	}

	public void setFrameDelay(int frameDelay) {
		this.frameDelay = frameDelay;
		this.targetFps = 1000 / frameDelay;
	}
	
	
}